<template>
  <div>
    <div class="zixuan_mother">
      <el-table
        @row-click="cellClicks"
        :data="tableData"
        style="width: 100%"
        header-row-class-name="header_stock"
        :max-height="height"
        class="stock_list_table"
        @sort-change="sortFor"
        :cell-class-name="tableCellClass"
        ref="chatContent"
      >
        <el-table-column
          fixed
          :label="$t('zixuanStock.zixuan_list.56i00jp2g4w0')"
          min-width="50"
          class-name="stock_list_left"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column
          fixed
          :label="$t('m.StockCode')"
          min-width="120"
          class-name="stock_list_left"
          prop="symbol"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.symbol }}</template>
        </el-table-column>
        <el-table-column
          fixed
          :label="$t('zixuanStock.zixuan_list.56i00jp2gm40')"
          min-width="150"
          class-name="stock_list_left"
          prop="name"
          align="center"
        >
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <!-- 最新价 -->
        <el-table-column
          :label="$t('m.latestPrice')"
          sortable="custom"
          prop="latestPrice"
          class-name="stock_list_center"
          min-width="100"
        >
          <template slot-scope="scope">
            <div
              :class="
                scope.row.gain > 0 ? 'red' : scope.row.gain == 0 ? '' : 'green'
              "
            >
              {{ scope.row.latestPrice | toFixed(scope.row.precision) }}
            </div>
          </template>
        </el-table-column>
        <!-- 涨跌额 -->
        <el-table-column
          :label="$t('zixuanStock.zixuan_list.56i00jp2gq80')"
          class-name="stock_list_center"
          sortable="custom"
          prop="chg"
          min-width="100"
        >
          <template slot-scope="scope">
            <h2
              :class="
                scope.row.gain > 0 ? 'red' : scope.row.gain == 0 ? '' : 'green'
              "
            >
              <span>
                {{ scope.row.chg > 0 ? "+" : ""
                }}{{ Number(scope.row.chg).toFixed(scope.row.precision) }}
              </span>
            </h2>
          </template>
        </el-table-column>
        <el-table-column
          :label="$t('m.quoteChange')"
          class-name="stock_list_center"
          sortable="custom"
          prop="gain"
          min-width="100"
        >
          <template slot-scope="scope">
            <h2
              :class="
                scope.row.gain > 0 ? 'red' : scope.row.gain == 0 ? '' : 'green'
              "
            >
              <span>
                {{ scope.row.gain > 0 ? "+" : ""
                }}{{ Number(scope.row.gain * 100).toFixed(2) + "%" }}
              </span>
            </h2>
          </template>
        </el-table-column>
        <!-- 买入价 -->
        <!-- <el-table-column
          :label="$t('m.buyingPrice')"
          sortable="custom"
          prop=""
          class-name="stock_list_center"
          min-width="100"
          v-if="level != 0"
        >
          <template slot-scope="scope">
            <div>{{ Number(scope.row.bidPrice) | toFixed(3) }}</div>
          </template>
        </el-table-column> -->
        <!-- 卖出价 -->
        <!-- <el-table-column
          :label="$t('zixuanStock.zixuan_list.56i00jp2gt80')"
          sortable="custom"
          prop=""
          class-name="stock_list_center"
          min-width="100"
          v-if="level != 0"
        >
          <template slot-scope="scope">
            <div>{{ Number(scope.row.askPrice) | toFixed(3) }}</div>
          </template>
        </el-table-column> -->
        <!-- 买量 -->
        <!-- <el-table-column
          :label="$t('zixuanStock.zixuan_list.56i00jp2gvw0')"
          sortable="custom"
          prop=""
          class-name="stock_list_center"
          min-width="80"
          v-if="level != 0"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.bidVol }}</div>
          </template>
        </el-table-column> -->
        <!-- 卖量 -->
        <!-- <el-table-column
          :label="$t('zixuanStock.zixuan_list.56i00jp2gzc0')"
          sortable="custom"
          prop=""
          class-name="stock_list_center"
          min-width="80"
          v-if="level != 0"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.askVol }}</div>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="volume"
          :label="$t('m.Volume')"
          class-name="stock_list_center"
          sortable="custom"
          min-width="100"
        >
          <template slot-scope="scope"
            ><span v-if="scope.row.volume">
              {{ scope.row.volume | changeNum(te) }}
            </span>
            <span v-else>--</span></template
          >
        </el-table-column>
        <el-table-column
          prop="amount"
          :label="$t('m.Turnover')"
          class-name="stock_list_center"
          sortable="custom"
          min-width="100"
        >
          <template slot-scope="scope"
            ><span v-if="scope.row.amount">
              {{ scope.row.amount | changeNum(te) }}
            </span>
            <span v-else>--</span></template
          >
        </el-table-column>
        <!-- 股息 -->
        <el-table-column
          prop="dividend"
          :label="$t('m.dividend')"
          class-name="stock_list_center"
          sortable="custom"
          min-width="100"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.dividend != 0">{{
              Number(scope.row.dividend) | toFixed(3)
            }}</span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <!-- 今开 -->
        <el-table-column
          :label="$t('m.OpenToday')"
          sortable="custom"
          prop="open"
          class-name="stock_list_center"
          min-width="80"
        >
          <template slot-scope="scope">
            <div
              :class="
                scope.row.open > scope.row.close
                  ? 'red'
                  : scope.row.open < scope.row.close
                  ? 'green'
                  : ''
              "
            >
              <span v-if="scope.row.open">{{
                Number(scope.row.open) | toFixed(scope.row.precision)
              }}</span>
              <span v-else>--</span>
            </div>
          </template>
        </el-table-column>
        <!-- 昨收 -->
        <el-table-column
          :label="$t('m.closed_yesterday')"
          sortable="custom"
          prop="close"
          class-name="stock_list_center"
          min-width="110"
        >
          <template slot-scope="scope">
            <div>
              <span v-if="scope.row.close">{{
                Number(scope.row.close) | toFixed(scope.row.precision)
              }}</span>
              <span v-else>--</span>
            </div>
          </template>
        </el-table-column>
        <!-- 最高 -->
        <el-table-column
          :label="$t('m.highest')"
          sortable="custom"
          prop="high"
          class-name="stock_list_center"
          min-width="80"
        >
          <template slot-scope="scope">
            <div
              :class="
                scope.row.high > scope.row.close
                  ? 'red'
                  : scope.row.high < scope.row.close
                  ? 'green'
                  : ''
              "
            >
              <span v-if="scope.row.high">{{
                Number(scope.row.high) | toFixed(scope.row.precision)
              }}</span>
              <span v-else>--</span>
            </div>
          </template>
        </el-table-column>
        <!-- 最低 -->
        <el-table-column
          :label="$t('m.lowest')"
          sortable="custom"
          prop="low"
          class-name="stock_list_center"
          min-width="80"
        >
          <template slot-scope="scope">
            <div
              :class="
                scope.row.low > scope.row.close
                  ? 'red'
                  : scope.row.low < scope.row.close
                  ? 'green'
                  : ''
              "
            >
              <span v-if="scope.row.low">{{
                Number(scope.row.low) | toFixed(scope.row.precision)
              }}</span>
              <span v-else>--</span>
            </div>
          </template>
        </el-table-column>
        <!-- 换手率 -->
        <el-table-column
          prop="turnover"
          sortable="custom"
          :label="$t('m.TurnoverRate')"
          class-name="stock_list_center"
          min-width="100"
        >
          <template slot-scope="scope">{{
            scope.row.turnover == 0
              ? "--"
              : (scope.row.turnover * 100).toFixed(2) + "%"
          }}</template>
        </el-table-column>
        <!-- 振幅 -->
        <el-table-column
          :label="$t('m.amplitude')"
          sortable="custom"
          prop="amplitude"
          class-name="stock_list_center"
          min-width="110"
        >
          <template slot-scope="scope">
            {{
              scope.row.amplitude == 0
                ? "--"
                : (scope.row.amplitude * 100).toFixed(2) + "%"
            }}
          </template>
        </el-table-column>
        <!-- 市盈率 -->
        <el-table-column
          :label="$t('m.P_ratio')"
          sortable="custom"
          prop="pe"
          class-name="stock_list_center"
          min-width="100"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.pe">
              {{ Number(scope.row.pe) | toFixed(2) }}
            </div>
            <div v-else>--</div>
          </template>
        </el-table-column>
        <!-- 融资保证金率 -->
        <el-table-column
          :label="$t('zixuanStock.zixuan_list.56i00jp2h280')"
          prop=""
          class-name="stock_list_center"
          min-width="150"
        >
          <template slot-scope="scope">
            <div>
              {{
                scope.row.buyLongRate == 0
                  ? "--"
                  : (Number(scope.row.buyLongRate) * 100).toFixed(0) + "%"
              }}
            </div>
          </template>
        </el-table-column>
        <!-- 融券保证金率 -->
        <el-table-column
          :label="$t('zixuanStock.zixuan_list.56i00jp2h580')"
          prop=""
          class-name="stock_list_center"
          min-width="150"
        >
          <template slot-scope="scope">
            <div>
              {{
                scope.row.shortSellRate == 0
                  ? "--"
                  : (Number(scope.row.shortSellRate) * 100).toFixed(0) + "%"
              }}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
export default {
  props: ["sortList"],
  methods: {
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
  },
  inject: ["reload"],
  data() {
    return {
      height: null,
      tableData: [],
      group: [], // 自选股票数量
      lang: "", // 当前语言
      zixuanTime: null, //自选定时器
      CNLists: {
        toggleShow: true,
        order: ["", "DESC", "ASC"],
        name: "order",
        url: "/user.v1/optional/index", //
        submit: {
          type: "CN",
          field: "gain",
          sort: "DESC",
          isPositions: 0,
        },
      },
    };
  },
  mounted() {
    this.$nextTick(function () {
      if ((this.type = "hk")) {
        this.height = $(window).height() - 156;
      } else {
        this.height = $(window).height() - 165;
      }
      // console.log(this.$store.state.level,'111111')
    });
    var box = this.$refs.chatContent.bodyWrapper;
    box.addEventListener("scroll", this.paperScroll);
    this.lang = localStorage.getItem("lang");
    this.getdata();
    if (this.level != "")
      if (this.level.CN) {
        // 沪深行情等级为1，没有其他行情会员时，5秒定时刷新
        if (this.level.CN.level <= 1) {
          if (!this.zixuanTime) {
            this.zixuanTime = setInterval(() => {
              this.refreshCN(this.CNLists);
            }, 5000);
          }
        }
      }
  },
  beforeDestroy() {
    if (this.zixuanTime) {
      clearInterval(this.zixuanTime); //关闭
    }
  },
  methods: {
    cellClicks(row) {
      var StockData = {
        securityType: row.securityType,
        symbol: row.symbol,
        market: row.market,
      };
      this.$store.dispatch("SetStockData", StockData);
      this.$emit("ListClick", true);
    },
    sortFor(column) {
      // 数组中的元素需为以下三者之一：ascending 表示升序，descending 表示降序，null 表示还原为原始顺序
      this.sortList.submit.field = column.prop;
      this.sortList.submit.page = 1;
      if (column.order == "ascending") {
        this.sortList.submit.sort = "ASC";
      } else if (column.order == "descending") {
        this.sortList.submit.sort = "DESC";
      } else {
        this.sortList.submit.sort = "";
      }
      this.tableData = [];
      this.getdata();
    },
    getdata() {
      var _this = this;
      _this.$axios
        .post(_this.sortList.url, { ..._this.sortList.submit })
        .then((res) => {
          if (res.code == 1) {
            _this.tableData = res.data.list;
            _this.tableData.forEach(function (res) {
              res.latestPrice = parseFloat(res.latestPrice);
              res.chg = parseFloat(res.chg);
              res.gain = parseFloat(res.gain);
              res.volume = parseFloat(res.volume);
              res.amount = parseFloat(res.amount);
              res.dividend = parseFloat(res.dividend);
              res.open = parseFloat(res.open);
              res.pb = parseFloat(res.pb);
              res.pe = parseFloat(res.pe);
              res.close = parseFloat(res.close);
              res.low = parseFloat(res.low);
              res.high = parseFloat(res.high);
              res.amplitude = parseFloat(res.amplitude);
              res.totalShares = parseFloat(res.totalShares);
              res.buyLongRate = parseFloat(res.buyLongRate);
              res.shortSellRate = parseFloat(res.shortSellRate);
            });
            let wsList = _this.addWsList(_this.tableData);
            if (wsList.length > 0)
              _this.$store.dispatch("SetZixuanSub", JSON.stringify(wsList));
            this.$emit("getListNum", res.data.group);
            _this.group = res.data.group;
          } else {
            _this.$message.error(res.msg);
          }
        })
        .catch((error) => {});
    },
    // 5秒请求沪深接口
    refreshCN(list) {
      var _this = this;
      _this.$axios
        .post(list.url, { ...list.submit })
        .then((res) => {
          if (res.code == 1) {
            if (res.data.list.length > 0) {
              res.data.list.forEach((item) => {
                for (let i = 0; i < _this.tableData.length; i++) {
                  if (item.symbol == _this.tableData[i].symbol) {
                    if (item.latestPrice != _this.tableData[i].latestPrice) {
                      let isBreaths;
                      // 如果股票价格更新了5,4,3次时呼吸灯闪烁2,1,0不闪
                      if (
                        !_this.tableData[i].isBreath ||
                        _this.tableData[i].isBreath == 6
                      )
                        isBreaths = 6;
                      else isBreaths = _this.tableData[i].isBreath;
                      isBreaths = isBreaths - 2;
                      _this.$nextTick(() => {
                        _this.$set(_this.tableData, i, item);
                        _this.$set(_this.tableData[i], "isBreath", isBreaths);
                      });
                      break;
                    }
                  }
                }
              });
            }
          }
        })
        .catch((error) => {});
    },
    // 将自选股添加进自选订阅队列
    addWsList(list) {
      let wsList = [];
      list.forEach((item) => {
        let objs = {};
        if (item.market == "SZSE" || item.market == "SSE") {
          // 自选股票为沪深，且等级为2时放入推送
          if (this.level.CN && this.level.CN.level) {
            if (this.level.CN.level == 2) {
              this.$set(objs, "market", item.market);
              this.$set(objs, "securityType", item.securityType);
              this.$set(objs, "action", "Q");
              this.$set(objs, "symbol", item.symbol);
              wsList.push(objs);
            }
          }
        } else if (item.market == "HKEX") {
          // 自选股票为港股，且等级为2时放入推送
          if (this.level.HK && this.level.HK.level) {
            if (this.level.HK.level == 2) {
              this.$set(objs, "market", item.market);
              this.$set(objs, "securityType", item.securityType);
              this.$set(objs, "action", "Q");
              this.$set(objs, "symbol", item.symbol);
              wsList.push(objs);
            }
          }
        } else if (item.market == "US") {
          // 自选股票为美股，且等级为1时放入推送
          if (this.level.US && this.level.US.level) {
            if (this.level.US.level == 1) {
              this.$set(objs, "market", item.market);
              this.$set(objs, "securityType", item.securityType);
              this.$set(objs, "action", "Q");
              this.$set(objs, "symbol", item.symbol);
              wsList.push(objs);
            }
          }
        }
      });
      return wsList;
    },
    Refresh() {
      // this.$router.go(0);
      this.reload();
    },
    conversion(string) {
      return parseFloat(string);
    },
    // 呼吸灯
    tableCellClass({ row,  column, rowIndex, columnIndex }) {
        if (row.isBreath >= 3) {
          if(columnIndex == 3 || columnIndex == 4 || columnIndex == 5) {
            if (row.gain > 0) return "red_breathing";
            else if (row.gain < 0) return "green_breathing";
            else return "";
          }
          return "";
      }
    },
  },
  watch: {
    zixuanList: {
      handler(val, old) {
        var _this = this;
        if (val != "") {
          let data = JSON.parse(val);
          for (let i = 0; i < data.length; i++) {
            if (_this.tableData.length > 0) {
              for (let j = 0; j < _this.tableData.length; j++) {
                if (
                  _this.tableData[j].symbol == data[i].symbol &&
                  _this.tableData[j].market == data[i].market &&
                  _this.tableData[j].securityType == data[i].securityType
                ) {
                  if (data[i].gain && data[i].latestPrice) {
                    if (data[i].latestPrice != _this.tableData[j].latestPrice) {
                      let isBreaths;
                      // 如果股票价格更新了5,4,3次时呼吸灯闪烁2,1,0不闪
                      if (
                        !_this.tableData[j].isBreath ||
                        _this.tableData[j].isBreath == 6
                      )
                        isBreaths = 6;
                      else isBreaths = _this.tableData[j].isBreath;
                      isBreaths--;
                      _this.$nextTick(() => {
                        _this.$set(
                          _this.tableData[j],
                          "latestPrice",
                          data[i].latestPrice
                        );
                        _this.$set(_this.tableData[j], "gain", data[i].gain);
                        _this.$set(_this.tableData[j], "isBreath", isBreaths);
                      });
                    }
                    // 赋值后退出里层循环
                    break;
                  }
                }
              }
            }
          }
        }
      },
      deep: true,
    },
    // 若为沪深市场LV=1，或为全部自选5秒刷新
    sortList: {
      handler(val) {
        if (val.submit && (val.submit.type == "CN" || val.submit.type == "")) {
          if (this.level != "")
            if (this.level.CN) {
              // 沪深行情等级为1，没有其他行情会员时，5秒定时刷新
              if (this.level.CN.level <= 1) {
                if (!this.zixuanTime) {
                  this.zixuanTime = setInterval(() => {
                    this.refreshCN(this.CNLists);
                  }, 5000);
                }
              }
            }
        }
        if (val.submit && val.submit.type != "CN" && val.submit.type != "") {
          if (this.zixuanTime) {
            clearInterval(this.zixuanTime); // 非沪深自选关闭定时器
          }
        }
      },
      deep: true,
    },
    level: {
      handler(val) {
        if (val != "") {
          if (val.CN) {
            // 沪深行情等级为1，没有其他行情会员时，3秒定时刷新
            if (val.CN.level <= 1) {
              if (!this.zixuanTime) {
                this.zixuanTime = setInterval(() => {
                  this.refreshCN(this.CNLists);
                }, 5000);
              }
            }
          }
        }
      },
      deep: true,
    },
  },
  computed: {
    // 自选列表
    zixuanList() {
      return this.$store.state.wsModel.zixuanList;
    },
    level() {
      return this.$store.state.index.level;
    },
  },
};
</script>
<style lang="less">
// border-bottom: 1px solid #202431;
.zixuan_mother {
  background: @deepBg;
  box-sizing: border-box;
  position: relative;
  padding: 10px 20px 0 20px;
  .stock_list_table {
    .red_breathing {
      animation: glow3 3000ms ease-out infinite alternate;
      border-right: none !important;
    }
    .green_breathing {
      animation: glow3 3000ms ease-out infinite alternate;
      border-right: none !important;
    }
    @-webkit-keyframes glow3 {
      0% {
        opacity: 0.2;
      }
      50% {
        opacity: 0.5;
      }
      100% {
        opacity: 0.8;
      }
    }
    @keyframes glow3 {
      0% {
        opacity: 0.2;
      }
      50% {
        opacity: 0.5;
      }
      100% {
        opacity: 0.8;
      }
    }
    .header_stock {
      height: 40px;
    }
    .el-table__header {
      th {
        border-bottom: 1px solid @LightBorderLine;
        border-top: 1px solid @LightBorderLine;
        border-right: 1px solid @LightBorderLine;
      }
      th:first-child {
        border-left: 1px solid @LightBorderLine;
      }
      .cell {
        font-size: 12px;
        height: 100%;
        color: @Dark_gray !important;
        font-weight: normal;
        line-height: 35px;
      }
      .stock_list_right {
        .cell {
          text-align: left;
        }
      }
      .stock_list_center {
        .cell {
          text-align: left;
        }
      }
      .stock_list_left {
        background: @deepBg;
        .cell {
          text-align: left;
        }
      }
    }
    .el-table__body {
      cursor: pointer;
      .el-table__row {
        .stock_list_left {
          background: @deepBg;
          padding: 5px 0;
          .cell {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            text-align: left;
          }
          .stock_list_h2 {
            padding-left: 29px;
            position: relative;
            font-size: 12px;
            color: @fff;
            line-height: 20px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            p {
              display: -webkit-box;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 2; //需要控制的文本行数
              overflow: hidden;
            }
          }
          .stock_list_p {
            font-size: 12px;
            color: @fff;
            line-height: 16px;
          }
        }
        .stock_list_center {
          .cell {
            color: @fff;
            font-size: 12px;
            text-align: left;
          }
        }
        .stock_list_right {
          background: @deepBg;
          .cell {
            text-align: left;
            color: @fff;
            font-size: 14px;
            padding-right: 25px;
          }
        }
        td {
          border-right: 1px solid @LightBorderLine;
          border-bottom: 1px solid @LightBorderLine;
          .cell {
            font-size: 12px;
            color: @fff;
            line-height: 30px;
            h2 {
              font-size: 12px;
            }
          }
        }
        td:first-child {
          border-left: 1px solid @LightBorderLine;
        }
      }
      .el-table__row.hover-row {
        background: @sideColor;
        .stock_list_left {
          background: @sideColor;
        }
      }
    }
    .el-table__fixed {
      bottom: 8px !important;
    }
    .el-table__fixed::before {
      display: none;
    }
    .stock_list_left {
      background: @sideColor;
    }
  }
}
</style>